﻿using System;
using System.Threading.Tasks;
using Engine;
using Game.NetWork;
using Game.NetWork.Packages;
using Game;
using System.Collections.Generic;

namespace YS
{
    public class YSplace
    {
        public int sjx;
        public int sjy;
        public int sjz;
        public bool not_find;
        private readonly ComponentPlayer _player;
        private readonly bool _isAdmin;
        private readonly Action _triggerWuDi; // 新增触发无敌的回调
        public void SendMsgPack(ComponentPlayer componentPlayer, string text)
        {
            MessagePackage val = new MessagePackage((string)null, text, (byte)0, (List<byte>)null);
            val.To = componentPlayer.PlayerData.Client;
            CommonLib.Net.QueuePackage((IPackage)(object)val);
        }

        // 通过构造函数注入玩家组件和权限状态
        // 修改构造函数
        public YSplace(ComponentPlayer player, bool isAdmin, Action triggerWuDi)
        {
            _player = player;
            _isAdmin = isAdmin;
            _triggerWuDi = triggerWuDi; // 初始化回调
        }

        public string ExecuteCommand2(string[] messageData, bool wudiover2, Client m_client)
        {
            // 冷却校验（普通玩家）
            if (!_isAdmin && !wudiover2)
            {
                return "<c=red>传送间隔过短，请等待30秒后重试</c>";
            }

            // 参数校验
            if (messageData.Length != 2)
            {
                return "<c=red>格式错误！正确格式：/ys place";
            }

            // 执行随机传送
            string result = YS_place(m_client);
            return result;
        }

        public string YS_place(Client m_client)
        {
            ComponentPlayer componentPlayer = m_client.PlayerData.ComponentPlayer;

            if (componentPlayer?.ComponentBody == null)
            {
                SendMsgPack(_player, "<c=red>错误：无法获取玩家实体</c>");
                return "<c=red>系统错误：玩家实体丢失</c>";
            }

            not_find = true;
            sjx = sjy = sjz = 0;

            // 获取玩家当前坐标用于强制传送
            Vector3 currentPosition = componentPlayer.ComponentBody.Position;

            Task.Run(async () =>
            {
                try
                {
                    int attempts = 0;
                    while (not_find && attempts++ < 10)
                    {
                        not_find = false;
                        SJXZ(componentPlayer);
                        await Task.Delay(100);
                        SJY(componentPlayer, m_client);

                        if (!not_find)
                        {
                            //Console.WriteLine($"成功找到坐标：{sjx}, {sjy}, {sjz}");
                            TeleportPlayer(sjx, sjy, sjz);
                            SendMsgPack(_player, "<c=green>安全传送成功</c>");
                            new YSplaceTime().ResetCoolDown(_player);
                            return;
                        }
                    }

                    // ======== 强制传送逻辑 ========
                    if (not_find)
                    {
                        // 使用玩家当前Y坐标加100作为Y坐标，超过255改成200
                        int addedValue = (int)currentPosition.Y + 100;
                        sjy = addedValue > 255 ? 200 : addedValue;

                        // 重新生成XZ坐标
                        SJXZ(componentPlayer);

                        // 执行强制传送
                        TeleportPlayer(sjx, sjy, sjz);
                        SendMsgPack(_player, $"<c=red>强制传送至：[{sjx}, {sjy}, {sjz}]</c>\n" +
                                             $"<c=orange>警告：未进行地形安全检查！</c>");
                        Console.WriteLine($"强制传送坐标：{sjx}, {sjy}, {sjz}");
                        // 触发无敌保护和冷却
                        _triggerWuDi?.Invoke(); // 调用回调
                        // 更新冷却
                        new YSplaceTime().ResetCoolDown(_player);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"异步任务异常：{ex}");
                    SendMsgPack(_player, "<c=red>传送过程发生错误</c>");
                }
            });

            return "<c=yellow>正在寻找安全位置...</c>";
        }
        // 生成随机坐标的方法
        public void SJXZ(ComponentPlayer componentPlayer)
        {
            // 添加空值安全检查
            if (componentPlayer?.ComponentBody == null)
            {
                not_find = true;
                SendMsgPack(_player, "<c=red>错误：无法获取玩家坐标</c>");
                return;
            }

            // 获取玩家当前坐标并转换为整数
            Vector3 playerPos = componentPlayer.ComponentBody.Position;
            int baseX = (int)playerPos.X;  // 显式转换玩家X坐标
            int baseZ = (int)playerPos.Z;  // 显式转换玩家Z坐标

            const int GENERATE_RADIUS = 500;
            var random = new System.Random();

            // 在整数基础上生成随机坐标
            sjx = baseX + random.Next(-GENERATE_RADIUS, GENERATE_RADIUS);
            sjz = baseZ + random.Next(-GENERATE_RADIUS, GENERATE_RADIUS);

            // 输出调试信息（可选）
            //Console.WriteLine($"基于坐标 {playerPos.X}, {playerPos.Z} 生成新坐标：{sjx}, {sjz}");
        }
        // 排除法判断：只要不是空气(0)和水(18)岩浆92都视为地面
        private bool IsGroundBlock(int blockValue)
        {
            return blockValue != 0 && blockValue != 92 && blockValue != 18;
        }
        // 检查坐标是否安全的方法
        public void SJY(ComponentPlayer componentPlayer, Client m_client)
        {
            for (int num = 180; num >= 0; num--) // 
            {
                int cellValue = m_client.SubsystemPlayers.m_subsystemTerrain.Terrain.GetCellValue(sjx, num, sjz);
                if (IsGroundBlock(cellValue))
                {
                    sjy = num + 5; // 如果找到地面，将Y坐标设置为地面高度加5
                    break; // 退出循环
                }
            }

            if (sjy == 0) // 如果Y坐标仍然是0，说明没有找到合适的地面
            {
                not_find = true; // 标记为未找到合适位置
                return; // 退出方法
            }

            not_find = false; // 标记为已找到合适位置
            TeleportPlayer(sjx, sjy, sjz); // 执行传送
        }
        public void CheckIfPositionFound()
        {
            if (not_find)
            {
                // 如果未找到合适位置，发送提示信息
                SendMsgPack(_player, "<c=red>未找到合适的传送位置，请稍后重试</c>");
                Console.WriteLine("未找到合适位置，请稍后重试");
            }
            else
            {
                // 如果找到合适位置，发送成功提示
                SendMsgPack(_player, "<c=green>成功传送到安全位置</c>");
                Console.WriteLine("成功传送到安全位置");
            }
        }
        // 执行传送
        private void TeleportPlayer(int x, int y, int z)
        {
            _player.ComponentBody.Position = new Vector3(x, y, z);
            CommonLib.Net.QueuePackage(new ComponentPlayerPackage(
                _player,
                ComponentPlayerPackage.PlayerAction.PositionSet
            ));
        }
    }
}